<?php

Raise::load('core.RaiseObject');
Raise::load('core.io.file.RaiseFile');
Raise::load('core.io.file.RaisePath');
Raise::load('RaiseAction');

/**
 * RaiseActionManager Class
 * The manager for RaiseAction to allow loading and executing RaiseAction
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core.action
 * @since 1.2
 */
class RaiseActionManager extends RaiseObject {
   
    /**
     * The RaiseApplication that this manager is working for
     * @var RaiseApplication
     */
    private $application;
    
    /**
     * Create a new RaiseActionManager
     * @param RaiseApplication $app The application that this manager will work for
     */
    public function __construct($app){
        $this->application = $app;
    }

    /**
     * Load a RaiseAction
     * @param string $p The package + class identifier
     * @param array|RaiseCollection $args Parameters passed to the RaiseAction
     * @return RaiseAction 
     */
    public function loadAction($p, $args = array()){
        $p = str_replace(array('\.','.', '%doDotToken$', '..'), array('%doDotToken$', DIRECTORY_SEPARATOR, '.', ''), $p);
        $pageClass = RaisePath::baseName($p);
        if (!class_exists($pageClass)) {
            $classPath = RaisePath::combine($this->application->rootPath(), 'raise/page/' . $p . '.php');
            $f = new RaiseFile($classPath);
            if($f->exists()){
                include($classPath);
            }
        }
        if (!class_exists($pageClass)) {
            $classPath = RaisePath::combine($this->application->rootPath(), 'raise/postback/' . $p . '.php');
            $f = new RaiseFile($classPath);
            if($f->exists()){
                include($classPath);
            }
        }
        if (class_exists($pageClass)) {
            $pc = new $pageClass($args);
            if($pc instanceof RaiseAction){
                return $pc;
            }
        }
        return null;
    }
    
    /**
     * Execute a RaiseAction
     * @param RaiseAction $action
     */
    public function doAction($action){
        $this->application->checkPermissions(get_class($action));
        $action->action($this->application);
        $action->header($this->application->response()->headers());
        $o = $action->output();
        if($this->application->csrfProtect() instanceof RaiseCsrfProtect){
            $o = $this->application->csrfProtect()->prepare($o);
        }
        $this->application->response()->body($o);
        $this->application->response()->output();
    }
    
}